package com.tiantianyuegou.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by ivany on 2016/2/29.
 */
public class LocationTools {
    private Context mContext;
    private LocationManager mLocationManager;
    private LocationChangeListener mLocationChangeListener;
    private AsyncHttpClient mHttpClient;

    public interface iLocationListener {
        void loactionSuccess(String cityName);
    }

    private iLocationListener mListener;

    public void setLocationListener(iLocationListener listener) {
        mListener = listener;
    }

    public LocationTools(Context context) {
        mContext = context;
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        mHttpClient = new AsyncHttpClient();
        mLocationChangeListener = new LocationChangeListener();
    }

    public void stopLocation() {
        Log.e("TAG","stop location");
        if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.removeUpdates(mLocationChangeListener);
        }
    }

    public void startLocation() {
        Log.e("TAG","start location");
        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        String provider = mLocationManager.getBestProvider(criteria, true); // 获取GPS信息
        Log.e("TAG","provider:"+provider);
        //GPS已经开启
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Log.e("TAG","have permission");
            if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                Location location = mLocationManager.getLastKnownLocation(provider); // 通过GPS获取位置
                if (location != null) {
                    Log.e("TAG", location.getLatitude() + ":" + location.getLongitude());
                    getCityByGPSLocation(location.getLatitude(), location.getLongitude());
                    mLocationManager.removeUpdates(mLocationChangeListener);
                }
                // 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
                mLocationManager.requestLocationUpdates(provider,1 * 1000, 500, mLocationChangeListener);
            }
        }else{
            Log.e("TAG","no permission");
        }
    }

    //调用百度地图的接口 ，获取城市名称
    private void getCityByGPSLocation(double latitude, double longitude) {
        Log.e("TAG","get city by gps location");
        String url = "http://api.map.baidu.com/geocoder?output=json&location="
                + latitude + "," + longitude + "&key=1WOjXfpIgo8rh4IqUl5VeYCb";
        mHttpClient.post(url, null, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Toast.makeText(mContext, "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                try {
                    Log.e("TAG", "get city name:" + s);
                    JSONObject root = new JSONObject(s);
                    String status = root.getString("status");
                    if ("OK".equals(status)) {
                        JSONObject result = root.getJSONObject("result");
                        JSONObject addressComponent = result.getJSONObject("addressComponent");
                        String city = addressComponent.getString("city");
                        Log.e("location city name :", city);
                        mListener.loactionSuccess(city);
                    } else {
                        Toast.makeText(mContext, "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class LocationChangeListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            getCityByGPSLocation(location.getLatitude(), location.getLongitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    }
}
